// pages/home/house_detail.js
var WxParse = require('../../wxParse/wxParse.js');
var that
var app = getApp();
Page({
  data: { 
    ad:{},
    productId:'',  //商品id
    pro:{},       //商品所有的相关信息 
    buynum:1,  //购买数量 

    select_typeid:'',  //选择的商品类别id
    s_not:0,  //1为点击购买弹出选规格框，2为加入购物车选规格框
    two_s:false,//规格弹窗是否同时加入购物车和购买
    fro:0,   //1为购物车进入申请界面返回，2为购买返回
    saled:false,  //当前的规格是否已卖
    zero_good:false,//是否所有规格都无货
  },
  onLoad: function (options) {
    that = this
    if (options.productId){
      that.setData({ productId: options.productId})
    }
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          h: res.windowHeight
        });
      }
    }); 
    // that.get_pro();
  },

  onShow: function () {
    that.get_pro();
    if (app.data.iswarm==1){
      app.data.iswarm=2;
      var e = { "currentTarget": { "dataset": {"status":1}}}
      if (that.data.fro == 1) { that.addShopCar(e);}
      if (that.data.fro == 2) { that.topay(e); }
    }
    if(that.data.saled){
      that.setData({ specs: '', select_typeid: '', max_num: "" })
    }
    
  },
  set_shop_type:function(){  //设置选择的类别
    var specs="";
    for (var i = 0; i < that.data.pro.specs.length; i++){
      for (var j = 0; j < that.data.pro.specs[i].items.length;j++){
        if (that.data.pro.specs[i].items[j].s==1){
          specs += that.data.pro.specs[i].items[j].id+'_'
        }
      }
    }
    specs = specs.substring(0, specs.length-1)
    for (var i = 0; i < that.data.pro.options.length; i++){
      if (that.data.pro.options[i].specs == specs){
        that.data.pro.goods.marketprice = that.data.pro.options[i].marketprice
        that.data.pro.goods.productprice = that.data.pro.options[i].productprice
        that.setData({pro:that.data.pro})

        that.setData({ specs: that.data.pro.options[i].title+"x"+that.data.buynum, select_typeid: that.data.pro.options[i].id, max_num: that.data.pro.options[i].stock});
        if (parseInt(that.data.pro.options[i].stock)<=0){
          that.setData({ specs: '', select_typeid: '', max_num:"不足" })
          app.toast_up("库存不足")
        }
        return; 
      } 
    }
    that.setData({ specs:'', select_typeid:'',max_num:""})
  },
  set_type_y: function (clickid) {   //设置商品类别样式
    var g_arr = [];  //将要置灰的规格子项
    if (clickid!="no"){
      for (var i = 0; i < that.data.pro.options.length; i++) {
        if (that.data.pro.options[i].stock == "0") {
          var g = that.data.pro.options[i].specs.split('_')
          // console.log(g)
          for(var j=0;j<g.length;j++){
            if (parseInt(g[j]) == clickid){  //点击的这个存在库存为0
                g.splice(j,1)
                // console.log(g)
                g_arr =g_arr.concat(g)
                // console.log(g_arr)
              }
          }
        }
      }
    }
    // console.log(that.data.pro.specs)
    for (var i = 0; i < that.data.pro.specs.length; i++) { 
      for (var j = 0; j < that.data.pro.specs[i].items.length; j++) {
        var t=true;
        for (var k = 0; k< that.data.pro.options.length; k++) {
          if (that.data.pro.options[k].specs.indexOf(that.data.pro.specs[i].items[j].id) >-1 && that.data.pro.options[k].stock!="0") {
            // console.log(that.data.pro.options[k])
            t=false //判断子项涉及到的是否都无货
          }
        }
        if (t) { g_arr=g_arr.concat(that.data.pro.specs[i].items[j].id)}
      }
    }

    // console.log(g_arr)
    for (var i = 0; i < that.data.pro.specs.length; i++) {
      for (var j = 0; j < that.data.pro.specs[i].items.length; j++) {
        if (that.contains(g_arr,that.data.pro.specs[i].items[j].id+'')){
          that.data.pro.specs[i].items[j].ggg=1
        }
        else { that.data.pro.specs[i].items[j].ggg = 0}
      }
    }
    that.setData({ pro: that.data.pro })
  },
  select_t:function(e){     //选择的商品分类
    // console.log(e.currentTarget.dataset.aid);
    // console.log(e.currentTarget.dataset.bid);

    if (e.currentTarget.dataset.ggg==1){ return }

    for(var i=0;i<that.data.pro.specs.length;i++){
      if (that.data.pro.specs[i].id == e.currentTarget.dataset.aid){
        for (var j = 0; j < that.data.pro.specs[i].items.length; j++) {
           that.data.pro.specs[i].items[j].s = 0;
          if (that.data.pro.specs[i].items[j].id == e.currentTarget.dataset.bid){
            that.data.pro.specs[i].items[j].s=1;  //被选中的样式
            // console.log(that.data.pro.specs[i].items[j].id)
            that.set_type_y(that.data.pro.specs[i].items[j].id);//设置
          } 
        }
      }
    }
    that.set_shop_type(); 
    that.setData({ pro: that.data.pro })
  },
  addShopCar:function(e){  //加入购物车  
    // console.log(e)
    if (app.data.person_msg_rr.level < 1 && app.data.iswarm == 0) {
      wx.navigateTo({ url: '../member/application_member?f=goods_detail&fro=1'})
      return;
    }//若非会员则提示注册会员
    
    if (that.data.select_typeid!=''){
      app.req(app.local_url + "do=shop&p=cart&op=add", { "od": app.data.openid, "optionid": that.data.select_typeid, "id": that.data.productId, "total": that.data.buynum}, function (res) {
        // console.log(res)
        if (res.status == 1) {
          wx.showToast({ title: res.result.message, icon: 'success',  duration: 2000 });
          that.setData({ showModalStatus: false }); //加入成功就关闭规格窗
        } else if (res.status == 0) {
          app.toast_up(res.result)
        } else { 
          app.modal("错误提示", "网络错误，是否重试？", function (re) {
            if (re) {
              that.addShopCar(e)
            }
          })
        }
      })
    }
    if (that.data.select_typeid == ''){ 
      if (that.data.two_s){
        // app.toast_up("请选择规格！")
      }else{
        that.setModalStatus(e) //未选择类型就弹窗
        that.setData({ s_not: 2 })
        that.setData({ two_s: false }) //点击加入购物车弹出的选择框里就没有立即购买
      }
    } 
  
    
  },
  setModalStatus2:function(e){  //弹窗——产品参数
  
    var animation2 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation2 = animation2
    animation2.translateY(300).step();
    this.setData({
      animationData2: animation2.export()
    })
  
      this.setData({ showModalStatus2: true });

      setTimeout(function () {
      animation2.translateY(0).step()
      this.setData({ animationData2: animation2 })
      if (e.currentTarget.dataset.status == 0) {
        this.setData({ showModalStatus2: false });
      }
    }.bind(this), 200)
  },
  get_pro:function(){
    app.req(app.local_url + "do=shop&p=detail&id=" + that.data.productId, { "od": app.data.openid, "shop_id":wx.getStorageSync('shop_id')}, function (res) {
      console.log(res)
      if (res.status == 1) {
        that.setData({pro:res.result});
        that.setData({
          content: res.result.goods.content, //详情     
        });
        // console.log(res.result);

        if (res.result.options.length == 1 &&parseInt(that.data.pro.options[0].stock)>0){
          that.data.pro.specs[0].items[0].s = 1;
          that.setData({ specs: that.data.pro.options[0].title + "x" + that.data.buynum, select_typeid: that.data.pro.options[0].id, max_num: that.data.pro.options[0].stock });
          that.setData({ pro: that.data.pro });
        }
        var zero_good=0;
        for (var j = 0; j < res.result.options.length;j++){
          zero_good +=parseInt(res.result.options[j].stock)
        } 
        // console.log(zero_good);
        if (zero_good == 0) { that.setData({ zero_good:true})}
        that.set_type_y("no");//设置规格置灰
        WxParse.wxParse('ad', 'html', res.result.goods.content, that, 5);
      } else if (res.status == 0) {
        app.toast_up(res.result)
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.get_pro()
          }
        })
      }
    })
  },
  select_m:function(e){
    that.setData({two_s:true})
    that.setModalStatus(e)// 点击选择类型就弹窗
  },
  // 弹窗
  setModalStatus: function (e) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0 
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export()
    })
    
      if (e.currentTarget.dataset.status == 1){
        this.setData({ showModalStatus: true});
      }
   
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({animationData: animation})
      if (e.currentTarget.dataset.status == 0) {
        that.setData({ two_s: false })
           if (that.data.select_typeid == '' && !that.data.zero_good){
              app.toast_up("未选择规格！")
           }
        that.setData({ showModalStatus: false });
      }
      if (that.data.s_not == 1 && that.data.select_typeid != ''){
        that.topay();
        that.setData({s_not:0})
      } else if (that.data.s_not==2&& that.data.select_typeid !=''){
        that.addShopCar();
        that.setData({ s_not: 0 })
        }
    }.bind(this), 200) 
  },
  // 加减
  changeNum: function (e) {
    
    if (that.data.select_typeid == '') {
      that.setData({ buynum:1})
      app.toast_up("请先选择规格!");return
    }
    
    if (e.target.dataset.alphaBeta == 0) {
          if (this.data.buynum <= 1) {
            buynum: 1
          } else {
            this.setData({ buynum: this.data.buynum - 1 })
          };
    } else {
          if (that.data.max_num!=""&&that.data.buynum>=parseInt(that.data.max_num)){
            this.setData({ buynum: parseInt(that.data.max_num)})
            app.toast_up('库存不足！')
          }
          else{
            this.setData({ buynum: this.data.buynum + 1 })
          }
    };
    that.set_shop_type(); 
  },
  topay:function(e){  
    if (app.data.person_msg_rr.level< 1&&app.data.iswarm == 0) {//若非会员则提示注册会员
      wx.navigateTo({ url: '../member/application_member?f=goods_detail&fro=2'})
      return;
    }
    
    if (that.data.select_typeid != '') { 
        wx.navigateTo({   //购买付钱
          url: './shop_order?goodsid=' + that.data.productId + "&optionid=" + that.data.select_typeid + "&num=" + that.data.buynum 
        })
    }
    if (that.data.select_typeid == ''){
      if (that.data.two_s){
          // app.toast_up("请选择规格！")
      }else{
        that.setModalStatus(e)// 未选择类型就弹窗
        that.setData({s_not:1})
        that.setData({ two_s: false }) //点击购买弹出的选择框里就没有加入购物车
      }
    }
  
  },
 contains:function(arr, obj) {  
    var i = arr.length;  
    while(i--) {
      if (arr[i] === obj) {
        return true;
      }
    }  
    return false;  
  }  
})